/*政府端 -项目信息管理-详情*/
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:frametrim/activity/government/ProjectMessDetailsPage01.dart';
import 'package:frametrim/activity/government/ProjectMessDetailsPage03.dart';
import 'package:frametrim/activity/government/ProjectMessDetailsPage04.dart';
import 'package:frametrim/appviews/pojectMessMarkView.dart';
import 'package:frametrim/appviews/textToTextView.dart';
import 'package:frametrim/utility/Tools.dart';
import 'package:frametrim/utility/log_utils.dart';
import 'package:frametrim/utility/screen.dart';
import 'package:frametrim/utility/sq_color.dart';
import 'package:frametrim/views/appbar_black.dart';
import 'package:frametrim/views/background_view.dart';
import 'package:frametrim/views/mySliverAppBar.dart';
import 'package:get/get.dart';

import '../../http/ApiUtils.dart';
import '../../http/HttpManager.dart';
import '../../model/DistrictCommonM.dart';
import '../../model/ProjectMessManagerBasicM.dart';
import '../../views/MyUnderlineTabIndicator.dart';
import 'ProjectMessDetailsPage02.dart';


class ProjectMessManagerDetailsPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ProjectMessManagerDetailsState();
}

class ProjectMessManagerDetailsState
    extends State<ProjectMessManagerDetailsPage> with TickerProviderStateMixin {
  late String id;

  late TabController _tabController; //需要定义一个Controller

  late double? expandedHeight = 800;

  final List<Tab> myTabs = [
    Tab(text: '项目基本信息'),
    Tab(text: '项目专户信息'),
    Tab(text: '项目单位信息'),
    Tab(text: '班组信息')
  ];

  late ProjectMessManagerBasicRecords? data = null;

  //项目类别
  List<DepartmentList> mProjectTypelist = [];

  //管辖划分
  List<DepartmentList> mProjectDeptlist = [];

  //资金来源
  List<DepartmentList> mProjectMoneySourcelist = [];

  @override
  void initState() {
    super.initState();
    // 创建Controller
    _tabController = TabController(length: myTabs.length, vsync: this);
    Future.delayed(Duration(milliseconds: 1000), () {
      setState(() {
        //topWidget高度+marginTop(10)+MarginBottom(10)+地图(120)+分割(10)+标题高度(45)+目测缺少间隔(5)
        expandedHeight =
            globalKey.currentContext!.size!.height + 20.0 + 130 + 45 + 5;
        LogUtils.e("expandedHeight==${expandedHeight}");
      });
    });
    //获取项目类别 "PROJECT_TYPE"   获取管辖划分  "DEPT"
    getDistrictData("PROJECT_TYPE");
    //获取管辖划分
    getDistrictData("DEPT");
    //资金来源
    getDistrictData("PROJECT_MONEY_SOURCE");
  }

  @override
  Widget build(BuildContext context) {
    var args = Get.arguments;
    id = args['id'];
    if (data == null) {
      //获取基本信息
      getBasicData();
      return Scaffold(
        body: Container(),
      );
    }
    return Scaffold(
      backgroundColor: SQColor.color_background,
      body: AnnotatedRegion(
        value: SystemUiOverlayStyle.dark,
        child: Column(
          children: [
            AppbarCenterTitle(
              title: '项目详情',
              imgStr: 'image/imv_back.png',
              titleColor: SQColor.black,
              backgroundColor: Colors.white,
            ),
            Expanded(
                child: NestedScrollView(
                    headerSliverBuilder: (context, innerBoxIsScrolled) {
                      return <Widget>[
                        //取消topPadding
                        MySliverAppBar(
                          backgroundColor: SQColor.color_background,
                          toolbarHeight: 0,
                          //是否固定在顶部
                          pinned: true,
                          //是否随着滑动隐藏标题
                          floating: true,
                          expandedHeight: expandedHeight,
                          // expandedHeight: 700,
                          // toolbarHeight:
                          flexibleSpace: FlexibleSpaceBar(
                            // key: _flexibleSpaceBarKey,
                            //设置标题部分  收缩样式
                            collapseMode: CollapseMode.pin,
                            background: Container(
                              child: Column(
                                children: [
                                  TopWidget(),
                                  //地图
                                  mapWidget(),
                                ],
                              ),
                            ),
                          ),
                          bottom: PreferredSize(
                            preferredSize: Size(Screen.width - 24, 45),
                            child: buildTableWidget(),
                          ),
                        )
                      ];
                    },
                    body: Container(
                        margin: EdgeInsets.only(left: 10, right: 10),
                        padding: EdgeInsets.only(left: 10, right: 10),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(8),
                                bottomRight: Radius.circular(8)),
                            color: SQColor.white),
                        child: Flexible(
                          child:
                              TabBarView(controller: _tabController, children: [
                            PeojectMessDetailsPage01(
                                data, mProjectTypelist, mProjectDeptlist,mProjectMoneySourcelist),
                            PeojectMessDetailsPage02(data),
                            PeojectMessDetailsPage03(),
                            PeojectMessDetailsPage04()
                          ]),
                        ))))
          ],
        ),
      ),
    );
  }

  final GlobalKey globalKey = GlobalKey();

  /*顶部信息*/
  Widget TopWidget() {
    return BackgroundView(
      globalKey: globalKey,
      mHorizontalPadding: 12,
      mVerticalPadding: 10,
      mVerticalBottomMargin: 10,
      mVerticalTopMargin: 10,
      widget: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  //状态  在建等
                  buildStateWidget(),
                  SizedBox(height: 10),
                  Container(
                    child: Text(data!.project!.name!,
                        style: TextStyle(
                            fontSize: 18,
                            color: SQColor.color_3D3D3D,
                            fontWeight: FontWeight.bold)),
                  )
                ],
              )),
              SizedBox(width: 20),
              Image.asset(getStateImage(), width: 56, height: 56)
            ],
          ),
          TextToTextView('项目编码', Tools.TextNullToLine(data!.project!.id.toString())),
          TextToTextView('控尘系统中项目ID', Tools.TextNullToLine(data!.project!.dustControlCode)),
          TextToTextView('项目类别',
              Tools.getDistrictName(data!.project!.type, mProjectTypelist)),
          TextToTextView(
              '管辖划分',
              Tools.getDistrictName(
                  data!.project!.areaDivide, mProjectDeptlist)),
          TextToTextView('开工日期', Tools.TextNullToLine(data!.project!.startDate)),
          TextToTextView('建设单位', Tools.TextNullToLine(data!.projectInfo!.constructionUnitName)),
          TextToTextView(
              '施工单位', Tools.TextNullToLine(data!.projectInfo!.generalContractorEnterpriseName)),
          TextToTextView('监理单位',Tools.TextNullToLine(data!.projectInfo!.superviseUnitName)),
        ],
      ),
    );
  }

//项目状态  在建、停工、完工待验收、竣工、新批
  Widget buildStateWidget() {
    Widget? child;
    var state = data!.project!.state;
    if (state == 0) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_0052D9,
          fullrColor: SQColor.color_ECF2FE,
          content: '在建');
    } else if (state == 1) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_ED7B2F,
          fullrColor: SQColor.color_FEF3E6,
          content: '竣工');
    } else if (state == 2) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_E34D59,
          fullrColor: SQColor.color_FDECEE,
          content: '停工');
    } else if (state == 3) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_067945,
          fullrColor: SQColor.color_E8F8F2,
          content: '新批');
    } else if (state == 4) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_ED7B2F,
          fullrColor: SQColor.color_FEF3E6,
          content: '完工待验收');
    }
    return child!;
  }

  //获取审核状态   -1待完善 0待审核 1审核通过 2审核驳回
  //   var mCheckState='';
  String getStateImage() {
    var img = "";
    var mCheck = data!.project!.checkStatus;
    if (mCheck == -1) {
      img = "image/icon_details_need.png";
    } else if (mCheck == 0) {
      img = "image/icon_details_ing.png";
    } else if (mCheck == 1) {
      img = "image/icon_details_pass.png";
    } else if (mCheck == 2) {
      img = "image/icon_details_back.png";
    }
    return img;
  }

  //地图
  Widget mapWidget() {
    return BackgroundView(
      mVerticalTopMargin: 0,
      mVerticalBottomMargin: 10,
      widget: Container(
        height: 120,
      ),
    );
  }

//悬浮部分
  Widget buildTableWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8), topRight: Radius.circular(8)),
          color: SQColor.white),
      margin: EdgeInsets.only(left: 10, right: 10),
      height: 45,
      child: TabBar(
        controller: _tabController,
        tabs: myTabs,
        // 定义TabWeight,若数量和定义不一致会报错
        onTap: (int index) {
          print('Selected......$index');
        },
        //设置未选中时的字体颜色，tabs里面的字体样式优先级最高
        unselectedLabelColor: SQColor.color_90black,
        //设置未选中时的字体样式，tabs里面的字体样式优先级最高
        unselectedLabelStyle: TextStyle(fontSize: 16),
        //设置选中时的字体颜色，tabs里面的字体样式优先级最高
        labelColor: SQColor.color_90black,
        //设置选中时的字体样式，tabs里面的字体样式优先级最高
        labelStyle: TextStyle(fontSize: 16.0),
        //允许左右滚动
        isScrollable: true,
        indicator: MyUnderlineTabIndicator(
            borderSide: BorderSide(width: 3.0, color: SQColor.color_0052D9)),
      ),
    );
  }

  /**
   * 项目基本信息
   */
  void getBasicData() async {
    var map = Map<String, dynamic>();
    map["id"] = id;
    HttpManager.getInstance().addHeader().get(context, ApiUtils.projectDetails,
        params: map, successCallBack: (dataMap) {
      ProjectMessManagerBasicM model =
          ProjectMessManagerBasicM.fromJson(dataMap);
      setState(() {
        data = model.records!;
      });
    });
  }

  /**
   * 字典接口
   */
  getDistrictData(String commonCode) {
    var map = Map<String, dynamic>();
    map["commonCode"] = commonCode;
    HttpManager.getInstance()
        .addHeader()
        .postJson(context, ApiUtils.getDistrictCommon, params: map,
            successCallBack: (dataMap) {
      DistrictCommonM model = DistrictCommonM.fromJson(dataMap);
      var departmentList = model.records?.departmentList;
      //获取项目类别 "PROJECT_TYPE"   获取管辖划分  "DEPT"
      if (commonCode == "PROJECT_TYPE") {
        setState(() {
          mProjectTypelist.clear();
          mProjectTypelist.addAll(departmentList!);
        });
      } else if (commonCode == "DEPT") {
        setState(() {
          mProjectDeptlist.clear();
          mProjectDeptlist.addAll(departmentList!
          );
        });
      } else if (commonCode == "PROJECT_MONEY_SOURCE") {
        setState(() {
          mProjectMoneySourcelist.clear();
          mProjectMoneySourcelist.addAll(departmentList!);
        });
      }
    });
  }
}
